from flask import Flask, render_template, request, redirect, url_for, flash, session
import os
# 导入数据库工具
from database import get_db, close_connection, init_db
# 导入用户管理蓝图
from routes.users import user_bp
from routes.coefficients import coefficient_bp 
from routes.coefficients_category import coefficient_category_bp
from routes.factors_category import factor_category_bp 
from routes.factors import factor_bp
from routes.model_category import model_category_bp 
from routes.models import model_bp
from routes.inventory_category import inventory_category_bp
from routes.inventory import inventory_bp
from routes.inventory_models import inventory_models_bp
from routes.report_annual_emission import report_annual_emission_bp
from routes.report_fuel_consumption import report_fuel_consumption_bp
from routes.report_power import report_power_bp
from routes.report_thermal import report_thermal_bp
from routes.report_complete import report_complete_bp
from routes.board_general import board_general_bp


# 初始化Flask应用
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-here'
app.config['DATABASE'] = os.path.join(app.root_path, 'database.db')

# 注册数据库连接关闭函数
app.teardown_appcontext(close_connection)

# 注册用户管理蓝图
app.register_blueprint(user_bp)
app.register_blueprint(coefficient_bp)  # 注册系数管理蓝图
app.register_blueprint(coefficient_category_bp)
app.register_blueprint(factor_category_bp) 
app.register_blueprint(factor_bp) 
app.register_blueprint(model_category_bp) 
app.register_blueprint(model_bp)
app.register_blueprint(inventory_category_bp)
app.register_blueprint(inventory_bp)
app.register_blueprint(inventory_models_bp)
app.register_blueprint(report_annual_emission_bp)
app.register_blueprint(report_fuel_consumption_bp)
app.register_blueprint(report_power_bp)
app.register_blueprint(report_thermal_bp)
app.register_blueprint(report_complete_bp)
app.register_blueprint(board_general_bp)

# 首页路由
@app.route('/')
def index():
    return redirect(url_for('user.user_management'))  # 修改为正确的蓝图端点

@app.before_request
def require_login():
    allowed_routes = ['user.login', 'static']
    if request.endpoint not in allowed_routes and 'user_id' not in session:
        return redirect(url_for('user.login'))


# 应用入口
if __name__ == '__main__':
    app.run(debug=True)  # 添加debug=True参数
    # 修改为监听所有网络接口
    # app.run(host='0.0.0.0', port=8028, debug=False)    # 如果数据库不存在则初始化
    if not os.path.exists(app.config['DATABASE']):
        init_db(app)
